package com.ff.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ff.dto.DishDto;
import com.ff.entity.Dish;
import com.ff.entity.DishFlavor;
import com.ff.mapper.DishMapper;
import com.ff.service.DishFlavorService;
import com.ff.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    DishFlavorService dishFlavorService;

    /**
     * 新增菜品，同时保存对应的口味数据
     * @param dishDto
     */
    @Override
    public void saveWithFlavor(DishDto dishDto) {
        //保存菜品的基本信息到菜品表dish
        this.save(dishDto);
        //保存菜品口味数据到菜品口味表dish_flavor
        Long id = dishDto.getId();
        List<DishFlavor> list = dishDto.getFlavors();
        for(DishFlavor l:list){
            l.setDishId(id);
        }
        dishFlavorService.saveBatch(list);
    }

    @Override
    public DishDto getByIdWithFlavor(long id) {

        DishDto dishDto=new DishDto();
        //根据id查询菜品信息
        Dish dish = this.getById(id);

        BeanUtils.copyProperties(dish,dishDto);

        QueryWrapper queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("dish_id",dish.getId());
        List<DishFlavor> list = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(list);
        return dishDto;
    }

    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {
        //先更新菜品表
        this.updateById(dishDto);

        //先删除之前关于该菜品的口味信息再插入新的口味信息
        Long id = dishDto.getId();
        dishFlavorService.remove(new QueryWrapper<DishFlavor>().eq("dish_id",id));
        //插入新的口味信息
        List<DishFlavor> flavors = dishDto.getFlavors();
        for(DishFlavor dishFlavor:flavors){
            dishFlavor.setDishId(id);
        }
        dishFlavorService.saveBatch(flavors);
    }
}
